<template>
  <div class="department-container">
    <div class="app-container">
      <el-card>
        <UploadExcel :on-success="handleSuccess" />
      </el-card>
    </div>
  </div>
</template>
<script>
import { importEmployee } from '@/api/employees'
import { formatExcelDate } from '@/utils/index'
export default {
  methods: {
    // 读取文件
    async handleSuccess({ results, header }) {
      console.log('读出来的excel的内容是', results, header)
      this.tableData = results
      this.tableHeader = header
      // 转换格式后的数据
      try {
        const res = this.transExcel(results)
        await importEmployee(res)
        this.$message.success('导入成功')
        // 返回上一个页面
        this.$router.back()
      } catch (error) {
        this.$message.error(error.message)
      }
    },
    // 转化文件的格式
    transExcel(results) {
      const mapInfo = {
        '入职日期': 'timeOfEntry',
        '手机号': 'mobile',
        '姓名': 'username',
        '转正日期': 'correctionTime',
        '工号': 'workNumber',
        '部门': 'departmentName',
        '聘用形式': 'formOfEmployment'
      }
      const res = results.map(item => {
        // item => {"姓名": "小张","手机号": "13800000252","入职日期": 44505,"转正日期": 44892,"工号": "9002","部门": "总裁办"}
        // 获取所有的属性名
        const zhKeys = Object.keys(item)
        // zhKeys => ['姓名', '手机号', '入职日期', '转正日期', '工号', '部门']
        const obj = {}
        zhKeys.forEach(ele => {
          // zhKeys => '姓名'
          const enKeys = mapInfo[ele]
          if (enKeys === 'timeOfEntry' || enKeys === 'correctionTime') {
            obj[enKeys] = new Date(formatExcelDate(item[ele]))
          } else {
            // enKeys => username
            obj[enKeys] = item[ele]
          }
        })
        return obj
      })
      return res
    }
  }
}
</script>
